package net.lovesrc.allin.biz;

import com.github.kevinsawicki.http.HttpRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class FileService extends BaseService {

    public static final File OUT_TEMP_ROOT;

    static {
        if (SystemUtils.IS_OS_LINUX) {
            OUT_TEMP_ROOT = new File("/tmp/out");
        } else {
            OUT_TEMP_ROOT = new File("d:/tmp/out");
        }
        if (!OUT_TEMP_ROOT.exists()) {
            OUT_TEMP_ROOT.mkdirs();
        }
    }

    public File save(String url) throws IOException {
        String dirString = FilenameUtils.getFullPathNoEndSeparator(url)
                .replace(":", "_")
                .replace("/", "_")
                .replace(".", "_");
        File dir = new File(OUT_TEMP_ROOT, dirString);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filename = FilenameUtils.getName(url);
        File file = new File(dir, filename);
        if (!file.exists()) {
            byte[] bytes = HttpRequest.get(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36")
                    .bytes();
            FileUtils.writeByteArrayToFile(file, bytes);
        }
        return file;
    }

}
